package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Business;
import cn.wolfcode.qo.BusinessQueryObject;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IBusinessService;
import cn.wolfcode.util.FileUploadUtil;
import cn.wolfcode.util.RequiredPermission;
import cn.wolfcode.util.UserContext;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;

@Controller
@RequestMapping("/business")
public class BusinessController {
    @Autowired
    private IBusinessService  businessService;
    @Autowired
    private ServletContext servletContext;
    @RequestMapping("/list")
    @RequiredPermission(name="商户门店查询",expression = "business:list")
    public String list(Model model, @ModelAttribute("qo") BusinessQueryObject qo){
        PageInfo<Business> pageInfo = businessService.query(qo);
        model.addAttribute("pageInfo",pageInfo);
        return "business/list";


//                List<Business> businesss = businessService.listAll();
//        model.addAttribute("businesss",businesss);
//        return "business/list";  //找视图 / WEB-INF/views/business/list.jsp
    }
    @RequestMapping("/delete")
    @RequiredPermission(name="商户门店删除",expression = "business:delete")
    public String delete(Long id){
        if (id!=null) {
            businessService.delete(id);
        }
        return "redirect:/business/list";  //让浏览器重新发一次请求
    }
    @RequestMapping("/input")
    @RequiredPermission(name="商户门店新增或修改",expression = "business:input")
    public String input(Long id,Model model){
        if (id!=null) {
            Business business = businessService.get(id);
            model.addAttribute("business",business);
        }
        return "business/input";
    }

    @RequestMapping("/saveOrUpdate")
    @RequiredPermission(name="商户门店新增或修改",expression = "business:saveOrUpdate")
    public String saveOrUpdate(Business business, MultipartFile file) throws Exception {
        if (file!=null&&file.getSize()>0){
            if (StringUtils.hasLength(business.getLicenseImg())) {
                FileUploadUtil.deleteFile(servletContext.getRealPath(business.getLicenseImg()));
            }

            String realPath = servletContext.getRealPath("/");
            String imgUrl = FileUploadUtil.uploadFile(file, realPath);
            business.setLicenseImg(imgUrl);
        }

        if (business.getId()!=null) {
            businessService.update(business);
        }else {
          businessService.save(business);
        }
        return "redirect:/business/list";
    }
}
